package com.qc.book.web;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qc.book.dao.BookMapper;
import com.qc.book.dao.UserMapper;

public class BookServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	Logger logger = LoggerFactory.getLogger(userServlet.class);
	SqlSession session;
	BookMapper bm;
	
	@Override
	public void init(){
		logger.debug("初始化数据。。。");
		try {
			SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
			session = sf.openSession();
			bm = session.getMapper(BookMapper.class);
		} catch (IOException e) {	
			e.printStackTrace();
		}
	}
	
	@Override
	public void destroy(){
		logger.debug("销毁数据。。。");
		if (null != session) {
			session.commit();
			session.close();
		}
		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("action");
		if (null != action || "findPageBook".equals(action)) {
			this.findPageBook(request,response);
		}
	}

	private void findPageBook(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String str = request.getParameter("indexPage");
		if (null == str) {
			str = "1";
		}
		Integer indexPage = Integer.valueOf(str);//当前页数
		str = request.getParameter("pageSize");
		if (null == str) {
			str = "5";
		}
		Integer pageSize = Integer.valueOf(str);
		
		indexPage = (indexPage - 1) * pageSize;
		List<Map<String, Object>> bookList = bm.findPageBook(indexPage, pageSize);
		
		request.setAttribute("bookList", bookList);
		request.setAttribute("indexPage", indexPage);
		request.setAttribute("pageSize", pageSize);
		
		request.getRequestDispatcher("index.jsp").forward(request, response);
		
	}
}
